<template>
  <div class="register-modal-mask">
    <div class="register-modal">
      <el-icon class="register-modal-close" @click="$emit('close')">
        <svg viewBox="0 0 1024 1024" width="24" height="24"><path d="M195.2 195.2c-12.5 12.5-12.5 32.8 0 45.3L478.7 524.8 195.2 808.3c-12.5 12.5-12.5 32.8 0 45.3s32.8 12.5 45.3 0l283.5-283.5 283.5 283.5c12.5 12.5 32.8 12.5 45.3 0s12.5-32.8 0-45.3L569.3 524.8l283.5-283.5c12.5-12.5 12.5-32.8 0-45.3s-32.8-12.5-45.3 0L524.8 478.7 241.3 195.2c-12.5-12.5-32.8-12.5-45.3 0z" fill="#909399"/></svg>
      </el-icon>
      <el-card class="register-card">
        <el-form
          ref="registerFormRef"
          :model="registerForm"
          :rules="registerRules"
          label-width="80px"
          @submit.prevent="handleRegister"
        >
          <el-form-item label="用户名" prop="username">
            <el-input
              v-model="registerForm.username"
              placeholder="请输入用户名"
              clearable
            />
          </el-form-item>
          <el-form-item label="密码" prop="password_hash">
            <el-input
              v-model="registerForm.password_hash"
              type="password"
              placeholder="请输入密码"
              show-password
              clearable
            />
          </el-form-item>
          <el-form-item label="确认密码" prop="confirmPassword">
            <el-input
              v-model="registerForm.confirmPassword"
              type="password"
              placeholder="请再次输入密码"
              show-password
              clearable
            />
          </el-form-item>
          <el-form-item label="手机号" prop="phone">
            <el-input
              v-model="registerForm.phone"
              placeholder="请输入手机号"
              clearable
            />
          </el-form-item>
          <el-form-item label="验证码" prop="code">
            <el-input
              v-model="registerForm.code"
              placeholder="请输入验证码"
              clearable
            >
              <template #append>
                <el-button :disabled="codeBtnDisabled" @click="sendCode">{{ codeBtnText }}</el-button>
              </template>
            </el-input>
          </el-form-item>
          <el-form-item>
            <el-button
              type="primary"
              :loading="loading"
              @click="handleRegister"
              style="width: 100%"
            >
              注册
            </el-button>
          </el-form-item>
          <div class="form-footer">
            <span>已有账号？</span>
            <el-link type="primary" @click="handleShowLogin">立即登录</el-link>
          </div>
        </el-form>
      </el-card>
    </div>
  </div>
</template>

<script setup>
import { ref, reactive } from 'vue'
import { useRouter } from 'vue-router'
import { useUserStore } from '@/store/user'
import { ElMessage } from 'element-plus'
import request from '@/utils/request'

const router = useRouter()
const userStore = useUserStore()

const registerFormRef = ref()
const loading = ref(false)

const registerForm = reactive({
  username: '',
  password_hash: '',
  confirmPassword: '',
  phone: '',
  code: ''
})

const validateConfirmPassword = (rule, value, callback) => {
  if (value === '') {
    callback(new Error('请再次输入密码'))
  } else if (value !== registerForm.password_hash) {
    callback(new Error('两次输入密码不一致'))
  } else {
    callback()
  }
}

const registerRules = {
  username: [
    { required: true, message: '请输入用户名', trigger: 'blur' },
    { min: 3, max: 20, message: '用户名长度在3到20个字符', trigger: 'blur' }
  ],
  password_hash: [
    { required: true, message: '请输入密码', trigger: 'blur' },
    { min: 6, message: '密码长度不能少于6位', trigger: 'blur' }
  ],
  confirmPassword: [
    { required: true, validator: validateConfirmPassword, trigger: 'blur' }
  ]
  // 移除phone和code的校验
}

const codeBtnText = ref('获取验证码')
const codeBtnDisabled = ref(false)
let codeTimer = null

const sendCode = async () => {
  if (!registerForm.phone || !/^1[3-9]\d{9}$/.test(registerForm.phone)) {
    ElMessage.error('请输入正确的手机号')
    return
  }
  codeBtnDisabled.value = true
  codeBtnText.value = '发送中...'
  try {
    await request.post('/api/user/sendCode', { phone: registerForm.phone })
    ElMessage.success('验证码已发送')
    let seconds = 60
    codeBtnText.value = `${seconds}s后重试`
    codeTimer = setInterval(() => {
      seconds--
      codeBtnText.value = `${seconds}s后重试`
      if (seconds <= 0) {
        clearInterval(codeTimer)
        codeBtnText.value = '获取验证码'
        codeBtnDisabled.value = false
      }
    }, 1000)
  } catch (e) {
    codeBtnText.value = '获取验证码'
    codeBtnDisabled.value = false
  }
}

const handleRegister = async () => {
  if (!registerFormRef.value) return
  try {
    await registerFormRef.value.validate()
    loading.value = true
    const { confirmPassword, code, ...registerData } = registerForm
    // 注册接口只传username、password_hash、phone
    const result = await userStore.register({
      username: registerData.username,
      password_hash: registerData.password_hash,
      phone: registerData.phone
    })
    if (result.success) {
      ElMessage.success('注册成功，请登录')
      router.push('/login')
    } else {
      ElMessage.error(result.message || '注册失败')
    }
  } catch (error) {
    ElMessage.error('注册失败，请重试')
  } finally {
    loading.value = false
  }
}

const handleShowLogin = () => {
  emit('close')
  setTimeout(() => {
    if (typeof window !== 'undefined') {
      const event = new CustomEvent('show-login-dialog')
      window.dispatchEvent(event)
    }
  }, 200)
}
</script>

<style scoped>
.register-modal-mask {
  position: fixed;
  left: 0;
  top: 0;
  width: 100vw;
  height: 100vh;
  background: rgba(0,0,0,0.2);
  z-index: 9999;
  display: flex;
  align-items: center;
  justify-content: center;
}
.register-modal {
  position: relative;
  display: flex;
  align-items: center;
  justify-content: center;
}
.register-modal-close {
  position: absolute;
  right: 12px;
  top: 12px;
  cursor: pointer;
  z-index: 10;
}
.register-card {
  width: 400px;
}

.card-header {
  text-align: center;
}

.card-header h2 {
  margin: 0;
  color: #409eff;
}

.form-footer {
  text-align: center;
  margin-top: 20px;
}

.form-footer span {
  margin-right: 10px;
  color: #606266;
}
</style> 